package com.lt.schoolchat.controller;

import cn.hutool.core.io.FileUtil;
import com.github.tobato.fastdfs.domain.conn.FdfsWebServer;
import com.github.tobato.fastdfs.domain.fdfs.StorePath;
import com.github.tobato.fastdfs.service.FastFileStorageClient;
import com.lt.schoolchat.common.BaseResponse;
import com.lt.schoolchat.common.ErrorCode;
import com.lt.schoolchat.common.ResultUtils;
import com.lt.schoolchat.exception.BusinessException;
import com.lt.schoolchat.mananger.CosManager;
import com.lt.schoolchat.model.dto.file.UploadFileRequest;
import com.lt.schoolchat.model.enums.FileUploadBizEnum;
import com.lt.schoolchat.service.UserService;
import com.lt.schoolchat.utils.GreenImageScan;
import com.lt.schoolchat.utils.GreenVideoScan;
import com.lt.schoolchat.utils.MinioTemplate;
import io.swagger.annotations.Api;
import io.swagger.annotations.ApiOperation;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.transaction.annotation.Transactional;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestPart;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.multipart.MultipartFile;

import javax.annotation.Resource;
import javax.servlet.http.HttpServletRequest;
import java.util.Arrays;
import java.util.Map;

/**
 * @description: 文件接口
 * @author: ~Teng~
 * @date: 2023/3/16 10:32
 */
@RestController
@RequestMapping("/file")
@Slf4j
@Api(tags = "文件上传接口")
public class FileController {
    @Resource
    private UserService userService;
    @Resource
    private CosManager cosManager;
    @Resource
    private FastFileStorageClient client;
    @Resource
    private FdfsWebServer webServer;
    @Resource
    private GreenVideoScan greenVideoScan;
    @Resource
    private GreenImageScan greenImageScan;
    @Autowired
    private MinioTemplate minioTemplate;

    /**
     * 图片上传
     */
    @PostMapping("/upload/image")
    @ApiOperation("图片上传")
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<String> uploadImageFile(@RequestPart("file") MultipartFile multipartFile, UploadFileRequest uploadFileRequest, HttpServletRequest request) {
        String biz = uploadFileRequest.getBiz();
        FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
        if (fileUploadBizEnum == null) {
            throw new BusinessException(ErrorCode.PARAMS_ERROR);
        }
        // 校验图片文件
        validImageFile(multipartFile, fileUploadBizEnum);

        // 上传图片
        String url = null;
        url =  minioTemplate.putObjectToUrl(multipartFile);
        if(!url.isEmpty())
            return ResultUtils.success(url);
        else
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "上传失败");

        // 文件目录：根据业务、用户来划分
//        String uuid = RandomStringUtils.randomAlphanumeric(8);
//        String filename = uuid + "-" + multipartFile.getOriginalFilename();
//        String filepath = String.format("/%s/%s/%s", fileUploadBizEnum.getValue(), 1L, filename);
//        File file = null;

//        try {
//            // 上传文件
//            file = File.createTempFile(filepath, null);
//            multipartFile.transferTo(file);
//            File finalFile = file;
//            CompletableFuture.runAsync(() -> cosManager.putObject(filepath, finalFile));
//            String videoThumbnailUrl = FileConstant.COS_HOST + filepath;
//            // 返回可访问地址
//            return ResultUtils.success(videoThumbnailUrl);
//        } catch (Exception e) {
//            log.error("file upload error, filepath = " + filepath, e);
//            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
//        } finally {
//            if (file != null) {
//                // 删除临时文件
//                boolean delete = file.delete();
//                if (!delete) {
//                    log.error("file delete error, filepath = {}", filepath);
//                }
//            }
//        }
    }

    /**
     * 校验图片文件
     *
     * @param fileUploadBizEnum 业务类型
     */
    private void validImageFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 文件大小
        long fileSize = multipartFile.getSize();
        // 文件后缀
        String fileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 2 * 1024 * 1024L;
        if (FileUploadBizEnum.USER_AVATAR.equals(fileUploadBizEnum) || FileUploadBizEnum.USER_VIDEO_COVER.equals(fileUploadBizEnum)) {
            if (fileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片文件大小不能超过 2M");
            }
            if (!Arrays.asList("jpeg", "jpg", "svg", "png", "webp").contains(fileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "图片文件类型错误");
            }
        }
    }

    /**
     * 视频上传
     */
    @PostMapping("/upload/video")
    @ApiOperation("小视频上传")
    @Transactional(rollbackFor = Exception.class)
    public BaseResponse<String> uploadVideoFile(@RequestPart("file") MultipartFile multipartFile, UploadFileRequest uploadFileRequest) {
        String videoUrl = null;
        try {
            String biz = uploadFileRequest.getBiz();
            FileUploadBizEnum fileUploadBizEnum = FileUploadBizEnum.getEnumByValue(biz);
            if (fileUploadBizEnum == null) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR);
            }
            // 视频校验
            validVideoFile(multipartFile, fileUploadBizEnum);
            String videoFilename = multipartFile.getOriginalFilename();
            String suffixFilename = FileUtil.getSuffix(videoFilename);
            // 上传视频到 FastDFS
            StorePath storePath = client.uploadFile(multipartFile.getInputStream(), multipartFile.getSize(), suffixFilename, null);
            videoUrl = webServer.getWebServerUrl() + storePath.getFullPath();
            // 阿里云 视频审核
            Map videoMap = greenVideoScan.imageUrlScan(videoUrl);
            if (videoMap != null) {
                String suggestion = (String) videoMap.get("suggestion");
                if ("block".equals(suggestion)) {
                    // 含有违规内容
                    String reason = (String) videoMap.get("reason");
                    throw new BusinessException(ErrorCode.OPERATION_ERROR, "添加失败，原因：" + reason);
                }
            }
            return ResultUtils.success(videoUrl);
        } catch (Exception e) {
            log.error("file upload error, filepath = " + videoUrl, e);
            throw new BusinessException(ErrorCode.SYSTEM_ERROR, "上传失败");
        }
    }

    /**
     * 校验视频文件
     * @param multipartFile
     * @param fileUploadBizEnum
     */
    private void validVideoFile(MultipartFile multipartFile, FileUploadBizEnum fileUploadBizEnum) {
        // 视频大小
        long videoFileSize = multipartFile.getSize();
        // 文件后缀
        String videoFileSuffix = FileUtil.getSuffix(multipartFile.getOriginalFilename());
        final long ONE_M = 100 * 1024 * 1024L;
        if (FileUploadBizEnum.USER_VIDEO.equals(fileUploadBizEnum)) {
            if (videoFileSize > ONE_M) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "视频大小不能超过 100M");
            }
            if (!Arrays.asList("mp4", "avi", "mpeg", "flv", "wmv").contains(videoFileSuffix)) {
                throw new BusinessException(ErrorCode.PARAMS_ERROR, "视频文件类型错误");
            }
        }
    }

    @PostMapping("/upload/file/test")
    @ApiOperation("图片测试上传")
    public BaseResponse<String> uploadImageTest(@RequestPart("file") MultipartFile multipartFile){
        String url = null;
        url =  minioTemplate.putObjectToUrl(multipartFile);

        if(!url.isEmpty())
            return ResultUtils.success(url);
        else
            throw new BusinessException(ErrorCode.PARAMS_ERROR, "测试上传失败");
    }
}
